<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
    class="dialog-form-dynamic"
  >
    <div class="title">
      示例：（01）xxxxxxx（11）xxxxxx（17）xxxxxx（10）xxxxxx（21）xxxxxx
    </div>
    <el-form
      :model="dynamicValidateForm"
      ref="dynamicValidateForm2"
      label-width="100px"
      class="form-dynamic"
    >
      <el-form-item
        prop="type"
        label="规则类型"
        :rules="[
          { required: true, message: '请选择规则类型', trigger: 'change' },
        ]"
      >
        <el-select
          v-model="dynamicValidateForm.type"
          @change="selectChange"
          placeholder="请选择"
        >
          <el-option
            v-for="item in optionsType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <template v-if="dynamicValidateForm.type === 'GS1'">
        <el-form-item
          v-for="(rule, index) in dynamicValidateForm.coreProductRuleVOList2"
          :label="index > 4 ? `其他${index - 4}` : rule.ruleName"
          :key="rule.key"
          :prop="'coreProductRuleVOList2.' + index + '.value'"
        >
          <el-input disabled v-model="rule.ruleCode"></el-input>
          <el-input v-model="rule.ruleLength" disabled> </el-input>
        </el-form-item>
      </template>
      <template v-if="dynamicValidateForm.type === 'GS1_OTHER'">
        <el-form-item
          v-for="(rule, index) in dynamicValidateForm.coreProductRuleVOList"
          :label="index > 4 ? `其他${index - 4}` : rule.ruleName"
          :key="rule.key"
          :prop="'coreProductRuleVOList.' + index + '.value'"
        >
          <el-input
            type="number"
            max="999"
            maxlength="3"
            placeholder="请输入标识符"
            :disabled="rule.disabledCode"
            v-model="rule.ruleCode"
          ></el-input>
          <el-input-number
            v-model="rule.ruleLength"
            placeholder="请输入长度"
            :max="rule.max || 15"
            :min="rule.min || 0"
          >
          </el-input-number>
          <el-button v-if="!rule.disabledCode" @click.prevent="removeRule(rule)"
            >删除</el-button
          >
        </el-form-item>
      </template>
      <el-form-item v-if="dynamicValidateForm.type === 'GS1_OTHER'">
        <el-button class="btn-dashed" @click="addRule">
          <i class="el-icon-plus" />添加其他
        </el-button>
      </el-form-item>
    </el-form>
  </page-dialog>
</template>

<script setup name="SelectBarCodeRules">
import PageDialog from '@/components/PageDialog/index'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  showDialog: {
    type: Boolean,
  },
  getCoreProductRule: {
    type: Object,
    default: undefined,
  },
})

let shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})
const optionsType = ref([
  {
    value: 'GS1_OTHER',
    label: '自定义规则',
  },
  {
    value: 'GS1',
    label: 'GS1规则',
  },
])
const dynamicValidateForm = ref({
  coreProductRuleVOList: [
    {
      ruleName: '产品编码',
      ruleCode: '01',
      ruleLength: '',
      max: 14,
      min: 13,
      disabledCode: true,
    },
    {
      ruleName: '生产批号',
      ruleCode: '10',
      ruleLength: '',
      max: 15,
      min: 0,
      disabledCode: true,
    },
    {
      ruleName: '生产日期',
      ruleCode: '11',
      ruleLength: '',
      max: 6,
      min: 0,
      disabledCode: true,
    },
    {
      ruleName: '失效日期',
      ruleCode: '17',
      ruleLength: '',
      max: 6,
      min: 0,
      disabledCode: true,
    },
    {
      ruleName: '序列号',
      ruleCode: '21',
      ruleLength: '',
      max: 15,
      min: 0,
      disabledCode: true,
    },
  ],
  coreProductRuleVOList2: [
    {
      ruleName: '产品编码',
      ruleCode: '01',
      ruleLength: '13',
    },
    {
      ruleName: '生产批号',
      ruleCode: '10',
      ruleLength: '20',
    },
    {
      ruleName: '生产日期',
      ruleCode: '11',
      ruleLength: '6',
    },
    {
      ruleName: '失效日期',
      ruleCode: '17',
      ruleLength: '6',
    },
    {
      ruleName: '序列号',
      ruleCode: '21',
      ruleLength: '5',
    },
  ],
  type: '',
})
// 弹窗相关
const dialogInfo = ref({
  title: '原厂码规则',
  btLoading: false,
  width: '30%',
  btList: [
    {
      label: '关闭',
      event: handleClose,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      // disabled: true,
      event: () => submitForm('dynamicValidateForm2'),
      show: true,
    },
  ],
})

function addRule() {
  dynamicValidateForm.value.coreProductRuleVOList.push({
    ruleName: '其他',
    ruleCode: '',
    ruleLength: '',
    disabledCode: false,
    key: Date.now(),
  })
  proxy.$forceUpdate()
}
function removeRule(item) {
  var index = dynamicValidateForm.value.coreProductRuleVOList.indexOf(item)
  if (index !== -1) {
    dynamicValidateForm.value.coreProductRuleVOList.splice(index, 1)
  }
  proxy.$forceUpdate()
}
function selectChange() {
  if (
    dynamicValidateForm.value.type === 'GS1_OTHER' &&
    (!dynamicValidateForm.value.coreProductRuleVOList ||
      dynamicValidateForm.value.coreProductRuleVOList.length < 5)
  ) {
    dynamicValidateForm.value.coreProductRuleVOList = [
      {
        ruleName: '产品编码',
        ruleCode: '01',
        ruleLength: '',
        max: 14,
        min: 13,
        disabledCode: true,
      },
      {
        ruleName: '生产批号',
        ruleCode: '10',
        ruleLength: '',
        max: 15,
        min: 0,
        disabledCode: true,
      },
      {
        ruleName: '生产日期',
        ruleCode: '11',
        ruleLength: '',
        max: 6,
        min: 0,
        disabledCode: true,
      },
      {
        ruleName: '失效日期',
        ruleCode: '17',
        ruleLength: '',
        max: 6,
        min: 0,
        disabledCode: true,
      },
      {
        ruleName: '序列号',
        ruleCode: '21',
        ruleLength: '',
        max: 15,
        min: 0,
        disabledCode: true,
      },
    ]
  }
}
function stringFillCharacter(length) {
  return new Array(length + 1).join('x')
}
function submitForm(formName) {
  proxy.$refs[formName].validate((valid) => {
    if (valid) {
      let params = {
        value: dynamicValidateForm.value.type,
        g1: dynamicValidateForm.value.coreProductRuleVOList,
      }
      if (dynamicValidateForm.value.type === 'GS1_OTHER') {
        const eg = []
        dynamicValidateForm.value.coreProductRuleVOList.map((item) => {
          eg.push(
            String(
              '(' +
                item.ruleCode +
                ')' +
                stringFillCharacter(Number(item.ruleLength))
            )
          )
          delete item.disabledCode
          delete item.key
          return item
        })
        delete dynamicValidateForm.value.coreProductRuleVOList2;
        params = {
          value: eg.toString().replace(/,/g, ''),
          g1: dynamicValidateForm.value,
        }
      } else {
        delete dynamicValidateForm.value.coreProductRuleVOList
        params = {
          value: 'GS1规则',
          g1: dynamicValidateForm.value,
        }
      }
      emits('callback', params)
      handleClose()
    } else {
      console.log('error submit!!')
      return false
    }
  })
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
onMounted(() => {
  if (props.getCoreProductRule && props.getCoreProductRule.type) {
    if (props.getCoreProductRule.type === 'GS1_OTHER') {
      props.getCoreProductRule.coreProductRuleVOList =
        props.getCoreProductRule.coreProductRuleVOList.map((item, index) => {
          if (index < 5) {
            item.disabledCode = true
          }
          if (item.ruleCode == '01') {
            item.max = 14
            item.min = 13
          }
          return item
        })
    }
    dynamicValidateForm.value = props.getCoreProductRule
  }
  dynamicValidateForm.value.coreProductRuleVOList2 = [
    {
      ruleName: '产品编码',
      ruleCode: '01',
      ruleLength: '13/14',
    },
    {
      ruleName: '生产批号',
      ruleCode: '10',
      ruleLength: '20',
    },
    {
      ruleName: '生产日期',
      ruleCode: '11',
      ruleLength: '6',
    },
    {
      ruleName: '失效日期',
      ruleCode: '17',
      ruleLength: '6',
    },
    {
      ruleName: '序列号',
      ruleCode: '21',
      ruleLength: '5',
    },
  ]
})
</script>

<style scoped lang="scss">
:deep(.el-dialog__body) {
  //   height: 355px;
  display: flex;
  flex-direction: column;
}

.title {
  margin-bottom: 20px;
}

.form-dynamic {
  max-height: 400px;

  .el-form-item__content {
    display: flex;
    justify-content: space-between;

    .el-input {
      width: 130px;
      margin-right: 5px;
    }

    .el-select {
      width: 262px;
    }
  }

  .btn-dashed {
    width: 100%;
    color: rgba(0, 0, 0, 0.65);
    background: #fff;
    border-color: #d9d9d9;
    border-style: dashed;

    .el-icon-plus {
      margin-right: 5px;
    }
  }
}
</style>
